<?php
	session_start();

	$response;
	$userId;

	changePassword();

	function changePassword() {
		global $response, $userId;

		$userName = $_SESSION['userName'];
		$oldPassword = $_GET['oldPassword'];
		$newPassword = $_GET['newPassword'];

		$response = array (
			'success' => false
		);

		$userExists = false;
		
		$userFile = fopen('../userInfo/users.txt', 'r') or die("can't open the user info file");
		while(($buffer = fgets($userFile)) != false){
			$user = explode(",", $buffer);
			if($userName == $user[0]){
				$userId = trim($user[1]);
				$userExists = true;
				break;
			}
		}
		fclose($userFile);

		if(updatePassword($oldPassword, $newPassword)){
			$response['success'] = true;
		}

		echo json_encode($response);
	}

	function updatePassword($oldPassword, $newPassword){
		global $userId, $response;

		$userPasswords = file("../userInfo/passwords.txt", FILE_SKIP_EMPTY_LINES);
		foreach($userPasswords as $line_num => $user){
			$user = explode(",", $user);
			if(trim($user[1]) === $userId && trim($oldPassword) === trim($user[0])){
				$user[0] = $newPassword;
				$user = implode($user,',');
				$userPasswords[$line_num] = $user;
				$userPasswords = implode($userPasswords);
				updatePasswordFile($userPasswords);
				return true;
			}
		}

		return false;
	}

	function updatePasswordFile($userPasswordsString){
		$userPasswordsFile = fopen("../userInfo/passwords.txt", 'w+') or die("can't open user info file");
		fwrite($userPasswordsFile, $userPasswordsString);
		fclose($userPasswordsFile);
	}
?>